package controllers

import (
	"net/http"
	"strconv"
	
	"github.com/gin-gonic/gin"
	"myblog/configs"
	"myblog/models"
	"myblog/services"
	"myblog/utils"
)

type AdminController struct {
	service *services.ArticleService
	config  *configs.Config
}

func NewAdminController(service *services.ArticleService, config *configs.Config) *AdminController {
	return &AdminController{
		service: service,
		config:  config,
	}
}

func (c *AdminController) LoginPage(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "admin/login.html", nil)
}

func (c *AdminController) Login(ctx *gin.Context) {
	username := ctx.PostForm("username")
	password := ctx.PostForm("password")
	
	if username != c.config.Auth.Username || password != c.config.Auth.Password {
		ctx.HTML(http.StatusUnauthorized, "admin/login.html", gin.H{
			"error": "用户名或密码错误",
		})
		return
	}
	
	// 生成JWT令牌
	token, err := utils.GenerateJWT(username, c.config.JWT.Secret, c.config.JWT.Expiration)
	if err != nil {
		ctx.HTML(http.StatusInternalServerError, "admin/login.html", gin.H{
			"error": "系统错误，请稍后再试",
		})
		return
	}
	
	// 设置HTTP-only cookie
	ctx.SetCookie("auth_token", token, c.config.JWT.Expiration*3600, "/", "", false, true)
	
	ctx.Redirect(http.StatusFound, "/admin/articles")
}

func (c *AdminController) Logout(ctx *gin.Context) {
	// 清除cookie
	ctx.SetCookie("auth_token", "", -1, "/", "", false, true)
	ctx.Redirect(http.StatusFound, "/admin/login")
}

func (c *AdminController) ArticleList(ctx *gin.Context) {
	articles, err := c.service.GetAllArticlesForAdmin()
	if err != nil {
		ctx.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"error": "获取文章列表失败",
		})
		return
	}
	
	ctx.HTML(http.StatusOK, "admin/list.html", gin.H{
		"articles": articles,
		"username": ctx.MustGet("username").(string),
	})
}

func (c *AdminController) EditArticlePage(ctx *gin.Context) {
	idParam := ctx.Param("id")
	
	if idParam == "new" {
		ctx.HTML(http.StatusOK, "admin/edit.html", gin.H{
			"article": &models.Article{},
		})
		return
	}
	
	id, err := strconv.Atoi(idParam)
	if err != nil {
		ctx.HTML(http.StatusBadRequest, "error.html", gin.H{
			"error": "无效的文章ID",
		})
		return
	}
	
	article, err := c.service.GetArticleByID(uint(id))
	if err != nil {
		ctx.HTML(http.StatusNotFound, "error.html", gin.H{
			"error": "文章不存在",
		})
		return
	}
	
	ctx.HTML(http.StatusOK, "admin/edit.html", gin.H{
		"article": article,
	})
}

func (c *AdminController) SaveArticle(ctx *gin.Context) {
	idParam := ctx.PostForm("id")
	title := ctx.PostForm("title")
	content := ctx.PostForm("content")
	published := ctx.PostForm("published") == "on"
	
	var err error
	
	if idParam == "" {
		// 创建新文章
		_, err = c.service.CreateArticle(title, content, published)
	} else {
		// 更新现有文章
		id, err := strconv.Atoi(idParam)
		if err != nil {
			ctx.HTML(http.StatusBadRequest, "error.html", gin.H{
				"error": "无效的文章ID",
			})
			return
		}
		
		_, _ = c.service.UpdateArticle(uint(id), title, content, published)
	}
	
	if err != nil {
		ctx.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"error": "保存文章失败: " + err.Error(),
		})
		return
	}
	
	ctx.Redirect(http.StatusFound, "/admin/articles")
}

func (c *AdminController) DeleteArticle(ctx *gin.Context) {
	idParam := ctx.Param("id")
	
	id, err := strconv.Atoi(idParam)
	if err != nil {
		ctx.HTML(http.StatusBadRequest, "error.html", gin.H{
			"error": "无效的文章ID",
		})
		return
	}
	
	if err := c.service.DeleteArticle(uint(id)); err != nil {
		ctx.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"error": "删除文章失败: " + err.Error(),
		})
		return
	}
	
	ctx.Redirect(http.StatusFound, "/admin/articles")
}

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		auth, _ := ctx.Cookie("auth")
		if auth != "true" {
			ctx.Redirect(http.StatusFound, "/admin/login")
			ctx.Abort()
			return
		}
		ctx.Next()
	}
}